package com.anjian.action;

import java.util.List;

import com.anjian.taobao.TaobaoProxy;
import com.anjian.utils.PagingOption;
import com.anjian.utils.PagingResult;
import com.taobao.api.domain.Item;
import com.taobao.api.response.ItemsInventoryGetResponse;
import com.taobao.api.response.ItemsOnsaleGetResponse;

public class ItemsAction extends ActionBase {
	
	public static final int SCOPE_ONSALE = 0;
	public static final int SCOPE_INVENTORY = 1;
	
	private int scope = SCOPE_ONSALE;
	private PagingOption option;
	private PagingResult<Item> pagingItems;
	
	public String execute()
	{
		String sessionId = getSessionId();
		try
		{
			if (scope == SCOPE_ONSALE)
			{
				getOnsaleItems(sessionId);
			}
			else if (scope == SCOPE_INVENTORY)
			{
				getInventory(sessionId);
			}
		}
		catch (Exception e)
		{
			error(e);
		}
		return SUCCESS;
	}

	private long getOnsaleItems(String sessionId) throws Exception
	{
		ItemsOnsaleGetResponse onsales = TaobaoProxy.getOnSales(sessionId, option.getCurrentPage() + 1, option.getLimit(), null, null);
		if (onsales.isSuccess())
		{
			long total = onsales.getTotalResults();
			_log.info("onsale.total: " + total);
			List<Item> items = onsales.getItems();
			pagingItems = new PagingResult<Item>();
			pagingItems.setOption(option);
			pagingItems.setItems(items);
			pagingItems.setTotal(total);
			return total;
		}
		else
		{
			error(onsales);
//			if ("accesscontrol.limited-by-app-access-count".equals(onsales.getSubCode()))
//			{
//				throw new Exception("out-of-band");
//			}
		}
		return -1L;
	}
	
	private long getInventory(String sessionId) throws Exception
	{
		ItemsInventoryGetResponse inventory = TaobaoProxy.getInventory(sessionId, option.getCurrentPage() + 1, option.getLimit(), null, null, null);
		if (inventory.isSuccess())
		{
			long total = inventory.getTotalResults();
			_log.info("inventory.total: " + total);
			List<Item> items = inventory.getItems();
			pagingItems = new PagingResult<Item>();
			pagingItems.setOption(option);
			pagingItems.setItems(items);
			pagingItems.setTotal(total);
			return total;
		}
		else
		{
			error(inventory);
//			if ("accesscontrol.limited-by-app-access-count".equals(inventory.getSubCode()))
//			{
//				throw new Exception("out-of-band");
//			}
		}
		return -1L;
	}

	public void setOption(PagingOption option) {
		this.option = option;
	}

	public PagingOption getOption() {
		return option;
	}

	public void setScope(int scope) {
		this.scope = scope;
	}

	public int getScope() {
		return scope;
	}

	public void setPagingItems(PagingResult<Item> pagingItems) {
		this.pagingItems = pagingItems;
	}

	public PagingResult<Item> getPagingItems() {
		return pagingItems;
	}
}
